$(function(){
	listVip();// 查出所有会员，填充select框
	listBarber();//查出所有理发师，填充select框
	//listAdmin();//查出所有管理员，填充select框
	listService();//查出所有服务，填充select框
	listProduct();//查出所有产品，填充select框
	
	listDebts();//查出挂账记录，填充表格
})

function listVip(){
	$.ajax({
		type : "post",
		url : "listVip.action",
		dataType : "json",
		data : {},
		success : function(result){
			var data = eval("(" + result + ")");
			$(".selectVip").append('<option value="">请选择...</option>');
			
			for(var i = 0;i<data.length;i++) {
				var d = data[i];
				console.log("会员名字:"+d.name);
				$('.selectVip').append(
						'<option value="' + d.id + '">' + d.name + '</option>'
				);
			}
			
			// chosen可搜索选择框
			$(".select-chosen").chosen();
			
		}
	})
}
function listBarber(){
	$.ajax({
		type : "post",
		url : "listEmployee.action",
		dataType : "json",
		data : {},
		success : function(result){
			var data = eval("(" + result + ")");
			$(".selectBarber").append('<option value="">请选择...</option>');
			
			for(var i = 0;i<data.length;i++) {
				var d = data[i];
				console.log("理发师名字:"+d.name);
				$('.selectBarber').append(
						'<option value="' + d.id + '">' + d.name + '</option>'
				);
			}
			// chosen可搜索选择框
			$(".selectBarber").chosen();
			
		}
	})
}
function listAdmin(){
	$.ajax({
		type : "post",
		url : "listAdmin.action",
		dataType : "json",
		data : {},
		success : function(result){
			var data = eval("(" + result + ")");
			$(".selectAdmin").append('<option value="">请选择...</option>');
			
			for(var i = 0;i<data.length;i++) {
				var d = data[i];
				console.log("管理员名字:"+d.name);
				$('.selectAdmin').append(
						'<option value="' + d.id + '">' + d.name + '</option>'
				);
			}
			
		}
	})
}
function listService(){
	$.ajax({
		type : "post",
		url : "listService.action",
		dataType : "json",
		data : {},
		success : function(result){
			var data = eval("(" + result + ")");
			$("#sTable tbody").html('');
			
			for(var i = 0;i<data.length;i++) {
				var d = data[i];
				console.log("服务名称:"+d.name);
				$('#sTable tbody').append(
					'<tr>' + 
						'<td>' + d.id + '</td>' + 
						'<td>' + d.name + '</td>' + 
						'<td>' + d.price + '</td>' +
						'<td>' + 
							'<select>'+
								'<option value="1">1</option>'+
								'<option value="2">2</option>'+
								'<option value="3">3</option>'+
							'</select>'+
						'</td>' +						
						'<td>' + 
							'<div class="visible-md visible-lg hidden-sm hidden-xs action-buttons">' + 
								'<button onclick="addService(this)"' + 'class="btn btn-xs btn-info">' + 
								'<i class="icon-plus bigger-120"> 添加</i></button>' +		
							'</div>' + 
						'</td>' +
					'</tr>'
				);
			}
			// datatables 初始化
			var stable = $("#sTable").dataTable({				
				"paging":   false,
				"scrollY": "200px",
                "scrollCollapse": "true",
				"oLanguage" : { // 设置语言
					"sProcessing" : "正在加载中......",
					"sLengthMenu" : "每页显示 _MENU_ 条记录",
					"sZeroRecords" : "对不起，查询不到相关数据！",
					'sSearch' : '检索:',
					"sEmptyTable" : "表中无数据存在！",
					"sInfo" : "当前显示 _START_ 到 _END_ 条，共 _TOTAL_ 条记录",
					"sInfoFiltered" : "数据表中共为 _MAX_ 条记录",
					"oPaginate" : {
						"sFirst" : "首页",
						"sPrevious" : "上一页",
						"sNext" : "下一页",
						"sLast" : "末页"
						}
					}
			});	
		},
		error : function() {
			console.log("出现错误，请稍后重试！")
		}
	})
}
function listProduct(){
	$.ajax({
		type : "post",
		url : "listProduct.action",
		dataType : "json",
		data : {},
		success : function(result){
			var data = eval("(" + result + ")");
			$("#pTable tbody").html('');
			
			for(var i = 0;i<data.length;i++) {
				var d = data[i];
				console.log("产品名称:"+d.name);
				$('#pTable tbody').append(
					'<tr>' + 
						'<td>' + d.id + '</td>' + 
						'<td>' + d.name + '</td>' + 
						'<td>' + d.price + '</td>' +
						'<td>' + 
							'<select>'+
								'<option value="1">1</option>'+
								'<option value="2">2</option>'+
								'<option value="3">3</option>'+
							'</select>'+
						'</td>' +						
						'<td>' + 
							'<div class="visible-md visible-lg hidden-sm hidden-xs action-buttons">' + 
								'<button onclick="addProduct(this)" ' + 'class="btn btn-xs btn-info">' + 
									'<i class="icon-plus bigger-120"> 添加</i></button>' +		
							'</div>' + 
						'</td>' +
					'</tr>'
				);
			}
			// datatables 初始化
			var ptable = $("#pTable").dataTable({				
				"paging":   false,
				"scrollY": "200px",
                "scrollCollapse": "true",
				"oLanguage" : { // 设置语言
					"sProcessing" : "正在加载中......",
					"sLengthMenu" : "每页显示 _MENU_ 条记录",
					"sZeroRecords" : "对不起，查询不到相关数据！",
					'sSearch' : '检索:',
					"sEmptyTable" : "表中无数据存在！",
					"sInfo" : "当前显示 _START_ 到 _END_ 条，共 _TOTAL_ 条记录",
					"sInfoFiltered" : "数据表中共为 _MAX_ 条记录",
					"oPaginate" : {
						"sFirst" : "首页",
						"sPrevious" : "上一页",
						"sNext" : "下一页",
						"sLast" : "末页"
						}
					}
			});	
			
		},
		error : function() {
			console.log("出现错误，请稍后重试！")
		}
	})
}

// 总额
var sum = 0;

// btnObject是固定的！
function addService(btnObject){
	var id = $(btnObject).parent().parent().parent().children().eq(0).text();
	var name = $(btnObject).parent().parent().parent().children().eq(1).text();
	var price = $(btnObject).parent().parent().parent().children().eq(2).text();
	var count = $(btnObject).parent().parent().parent().children().eq(3).children().eq(0).val();
	console.log(id,name,price,count);
	
	$("#itemTable tbody").append(
		'<tr>' + 
			'<td>' + id + '</td>' + 
			'<td>' + name + '</td>' +
			'<td></td>' +
			'<td>' + price + '</td>' +
			'<td>' + count + '</td>' +						
			'<td>' + price*count + '</td>' +
			'<td>' + 
				'<button class="btn btn-xs btn-danger">' +
					'<i class="icon-trash bigger-120"></i>' +
				'</button>' +
			'</td>' + 
		'</tr>'
	);
	// 总额计算
	sum = sum + price*count;
	$("#sum").text(sum);
	$("#totalMo").text(sum);
	$("#totalMo2").text(sum);
	
	// 填充表格下方消费后卡余额
	var vipBeforeAmount = $("#vBeforeAmount").text();
	
	if (Number(vipBeforeAmount) > Number(sum)){
		var afterAmount = Number(vipBeforeAmount) - Number(sum);
		$("#vAfterAmount").text(afterAmount);
	} else {
		var afterAmount = "余额不足";
		$("#vAfterAmount").text(afterAmount);
	}
		
	// 在结算的模态框里添加
	$("#ItemMo").append(
		'<label class="col-sm-3"> 服务ID与名称 </label>'+ 
		'<input type="text" value="'+id+'" id="itemId" readonly="readonly"></input>'+
		'<input type="text" value="'+name+'" id="itemName" readonly="readonly"></input>'+
		'<hr>'+
		'<label class="col-sm-3"> 数量 </label>'+ 
		'<input type="text" value="'+count+'" id="itemCount" readonly="readonly"></input>'+
		'<hr>'+
		'<label class="col-sm-3"> 单价 </label>'+ 
		'<input type="text" value="'+price+'" id="itemPrice" readonly="readonly"></input>'+
		'<hr>'
	);
	$("#ItemMo2").append(
			'<label class="col-sm-3"> 服务ID与名称 </label>'+ 
			'<input type="text" value="'+id+'" id="itemId" readonly="readonly"></input>'+
			'<input type="text" value="'+name+'" id="itemName" readonly="readonly"></input>'+
			'<hr>'+
			'<label class="col-sm-3"> 数量 </label>'+ 
			'<input type="text" value="'+count+'" id="itemCount" readonly="readonly"></input>'+
			'<hr>'+
			'<label class="col-sm-3"> 单价 </label>'+ 
			'<input type="text" value="'+price+'" id="itemPrice" readonly="readonly"></input>'+
			'<hr>'
		);
	
};
function addProduct(btnObject){
	var id = $(btnObject).parent().parent().parent().children().eq(0).text();
	var name = $(btnObject).parent().parent().parent().children().eq(1).text();
	var price = $(btnObject).parent().parent().parent().children().eq(2).text();
	var count = $(btnObject).parent().parent().parent().children().eq(3).children().eq(0).val();
	console.log(id,name,price,count);
	
	
	$("#itemTable tbody").append(
		'<tr>' + 
			'<td>' + id + '</td>' + 
			'<td></td>' + 
			'<td>' + name + '</td>' + 			
			'<td>' + price + '</td>' +
			'<td>' + count + '</td>' +						
			'<td>' + price*count + '</td>' +
			'<td>' + 
				'<button class="btn btn-xs btn-danger">' +
					'<i class="icon-trash bigger-120"></i>' +
				'</button>' +
			'</td>' +
		'</tr>'
	);
	// 总额
	sum = sum + price*count;
	$("#sum").text(sum);
	$("#totalMo").text(sum);
	$("#totalMo2").text(sum);
	
	// 填充表格下方消费后卡余额
	var vipBeforeAmount = $("#vBeforeAmount").text();
	
	if (Number(vipBeforeAmount) > Number(sum)){
		var afterAmount = Number(vipBeforeAmount) - Number(sum);
		$("#vAfterAmount").text(afterAmount);
	} else {
		var afterAmount = "余额不足";
		$("#vAfterAmount").text(afterAmount);
	}
	
	// 在结算的模态框里添加
	$("#ProductMo").append(
		'<label class="col-sm-3"> 产品ID与名称 </label>'+ 
		'<input type="text" value="'+id+'" id="proId" readonly="readonly"></input>'+
		'<input type="text" value="'+name+'" id="proName" readonly="readonly"></input>'+
		'<hr>'+
		'<label class="col-sm-3"> 数量 </label>'+ 
		'<input type="text" value="'+count+'" id="proCount" readonly="readonly"></input>'+
		'<hr>'+
		'<label class="col-sm-3"> 单价 </label>'+ 
		'<input type="text" value="'+price+'" id="proPrice" readonly="readonly"></input>'+
		'<hr>'
	);
	$("#ProductMo2").append(
			'<label class="col-sm-3"> 产品ID与名称 </label>'+ 
			'<input type="text" value="'+id+'" id="proId" readonly="readonly"></input>'+
			'<input type="text" value="'+name+'" id="proName" readonly="readonly"></input>'+
			'<hr>'+
			'<label class="col-sm-3"> 数量 </label>'+ 
			'<input type="text" value="'+count+'" id="proCount" readonly="readonly"></input>'+
			'<hr>'+
			'<label class="col-sm-3"> 单价 </label>'+ 
			'<input type="text" value="'+price+'" id="proPrice" readonly="readonly"></input>'+
			'<hr>'
		);
}

// 经手人改变，填充模态框
//function stuffChange(){
//	var stuffVal = $(".selectAdmin").val();
//	$("#stuffMan").text(stuffVal);
//	$("#payAdmin").text(stuffVal);
//	$("#stuffMan2").text(stuffVal);//结算
//	$("#payAdmin2").text(stuffVal);//结算
//}
//会员改变，填充结算模态框，以及表格下面列出余额。同时填充admin。
function vipChange(){
	var vipVal = $(".theVip").val();
	console.log(vipVal);
	$("#vipMan").text(vipVal);
	$("#vipMan2").text(vipVal);//结算
	
	// 填充表格下面的储值卡余额数目
	$.ajax({
		type : "post",
		url : "getOneVip.action",
		dataType : "json",
		data : {
			"vip.id" : vipVal
		},
		success : function(result){
			var data = eval("(" + result + ")");
			
			$("#vBeforeAmount").text(data[0].amount);
		},
		error : function() {
			console.log("出现错误，请稍后重试！")
		}
	})
	
	var adminName = $("#adminName").val();
	console.log("adminName:" + adminName);
	// 填充admin
	$.ajax({
		type : "post",
		url : "findByName.action",
		dataType : "json",
		data : {
			"admin.name" : adminName
		},
		success : function(result){
			var data = eval("(" + result + ")");
			$("#stuffMan").text(data[0].id);
			$("#payAdmin").text(data[0].id);
			$("#stuffMan2").text(data[0].id);//结算
			$("#payAdmin2").text(data[0].id);//结算
		},
		error : function() {
			console.log("出现错误，请稍后重试！")
		}
	})
	
}
//理发师改变，填充模态框
function barberChange(){
	var barberVal = $(".selectBarber").val();
	$("#barberMan").text(barberVal);
	$("#barberMan2").text(barberVal);//结算
}
// 填充模态框的订单号
function changeSON(btnObject){
//	var timestamp = Date.parse(new Date());
//	var son = "so"+timestamp;
	var date = new Date();
	var son = "10"+date.getMinutes()+date.getSeconds();
	$("#saleOrderNo").text(son);
	$("#saleOrderNo2").text(son);//结算
	
	// 查询vip的储值卡余额情况，跟消费金额比较
	var vId = $("#vipMan2").text();
	var amount = $("#totalMo2").text(); // 消费金额
	//console.log("vId:"+vId);
	$.ajax({
		type : "post",
		url : "getOneVip.action",
		dataType : "json",
		data : {
			"vip.id" : vId
		},
		success : function(result){
			var data = eval("(" + result + ")");
			
			$("#moVName").text(data[0].name);
			$("#moVAmount").text(data[0].amount);
			$("#moVConsumption").text(amount);
			
			if (Number(data[0].amount) > Number(amount)){
				var afterCon = Number(data[0].amount) - Number(amount);
				$("#moVAfterConsumption").text(afterCon);
			} else {
				var afterCon = 0;
				$("#moVAfterConsumption").text(afterCon);
			}
			
		},
		error : function() {
			console.log("出现错误，请稍后重试！")
		}
	})
	
}

// 确认支付的函数
function payment(btnObject){
	var saleON = $("#saleOrderNo").text(); // 订单号
	var vipId = $("#vipMan").text(); // 会员ID
	var total = $("#totalMo").text(); // 总金额
	var stuffId = $("#stuffMan").text(); // 经手人ID
	var status = $("#status").text(); // 状态
	var barberId = $("#barberMan").text(); // 理发师ID
 	
	var timestamp = Date.parse(new Date());
	var payNum = "pay"+timestamp;   // 支付编号
	
	var payTotal = total; // 支付金额现在先假定同总金额
	var payType = $(".typeMo").val(); //支付方式
	var payMan = stuffId; // 收款人现在先假定同经手人
	
	console.log(saleON,vipId,total,stuffId,status,barberId,payNum,payType);
	
	// 订单表记录的插入
	$.ajax({
		type : "post",
		url : "saveSaleOrder.action",
		dataType : "json",
		data : {
			"saleOrder.saleOrderNo" : saleON,
			"saleOrder.customerNo" : vipId,
			"saleOrder.total" : total,
			"saleOrder.stuff" : stuffId,
			"saleOrder.status" : "已交易",
			"saleOrder.barber" : barberId
		},
		success : function(result){
			//var data = eval("(" + result + ")");
			console.log("订单已保存！");
			
			// 订单明细记录的插入
			var ser = $("#ItemMo2");
			var pro = $("#ProductMo2");
			
			if(ser.children().eq(1).attr("id")=="itemId"){ //第一条服务明细
				// 获取服务id,名称，数量
				var serId = $("#ItemMo2").children().eq(1).val();
				var serName = $("#ItemMo2").children().eq(2).val();
				var serCount = $("#ItemMo2").children().eq(5).val();
				var serPrice = $("#ItemMo2").children().eq(8).val();
				$.ajax({
					type : "post",
					url : "saveSerSaleOrderItem.action",
					dataType : "json",
					data : {
						"saleOrderItem.saleOrderNo" : saleON,
						"saleOrderItem.itemId" : serId,
						
						"saleOrderItem.quantity" : serCount,
						"saleOrderItem.salePrice" : serPrice,
						"saleOrderItem.subTotal" : serPrice*serCount
					},
					success : function(){
						//var data = eval("(" + result + ")");
						console.log("订单明细已保存！")
						
					},
					error : function() {
						console.log("出现错误，请稍后重试！")
					}
				});
				
			}
			//如果有第二条服务
			if(ser.children().eq(11).attr("id")=="itemId"){ 
				// 获取服务id,名称，数量
				var serId = $("#ItemMo2").children().eq(11).val();
				var serName = $("#ItemMo2").children().eq(12).val();
				var serCount = $("#ItemMo2").children().eq(15).val();
				var serPrice = $("#ItemMo2").children().eq(18).val();
				$.ajax({
					type : "post",
					url : "saveSerSaleOrderItem.action",
					dataType : "json",
					data : {
						"saleOrderItem.saleOrderNo" : saleON,
						"saleOrderItem.itemId" : serId,
						
						"saleOrderItem.quantity" : serCount,
						"saleOrderItem.salePrice" : serPrice,
						"saleOrderItem.subTotal" : serPrice*serCount
					},
					success : function(){
						//var data = eval("(" + result + ")");
						console.log("订单明细已保存！")
						
					},
					error : function() {
						console.log("出现错误，请稍后重试！")
					}
				});	
			}
			// 第一条产品
			if($("#ProductMo2").children().eq(1).attr("id")=="proId"){ 
				console.log("有没有跳进插入产品")
				// 获取id,名称,数量,价格
				var proId = $("#ProductMo2").children().eq(1).val();
				var proName = $("#ProductMo2").children().eq(2).val();
				var proCount = $("#ProductMo2").children().eq(5).val();
				var proPrice = $("#ProductMo2").children().eq(8).val();
				$.ajax({
					type : "post",
					url : "saveProSaleOrderItem.action",
					dataType : "json",
					data : {
						"saleOrderItem.saleOrderNo" : saleON,
						"saleOrderItem.productId" : proId,
						
						"saleOrderItem.quantity" : proCount,
						"saleOrderItem.salePrice" : proPrice,
						"saleOrderItem.subTotal" : proPrice*proCount
					},
					success : function(){
						//var data = eval("(" + result + ")");
						console.log("订单明细已保存！")
						
					},
					error : function() {
						console.log("出现错误，请稍后重试！")
					}
				});	
			}
			// 如果有第二条产品
			if(pro.children().eq(11).attr("id")=="productId"){ 
				// 获取id,名称,数量,价格
				var proId = $("#ProductMo2").children().eq(11).val();
				var proName = $("#ProductMo2").children().eq(12).val();
				var proCount = $("#ProductMo2").children().eq(15).val();
				var proPrice = $("#ProductMo2").children().eq(18).val();
				$.ajax({
					type : "post",
					url : "saveProSaleOrderItem.action",
					dataType : "json",
					data : {
						"saleOrderItem.saleOrderNo" : saleON,
						"saleOrderItem.productId" : proId,
						
						"saleOrderItem.quantity" : proCount,
						"saleOrderItem.salePrice" : proPrice,
						"saleOrderItem.subTotal" : proPrice*proCount
					},
					success : function(){
						//var data = eval("(" + result + ")");
						console.log("订单明细已保存！")
						
					},
					error : function() {
						console.log("出现错误，请稍后重试！")
					}
				});	
			}
					
			// 支付表记录的插入
			$.ajax({
				type : "post",
				url : "savePayment.action",
				dataType : "json",
				data : {
					"payment.saleOrderNo" : saleON,
					"payment.paymentNo" : payNum,
					"payment.amount" : payTotal,
					"payment.payType" : payType,
					"payment.stuff" : stuffId	
				},
				success : function(result){
					//var data = eval("(" + result + ")");
					console.log("支付记录已保存！");
					
					// 减去储值卡余额的操作
					$.ajax({
						type : "post",
						url : "changeVipAmount.action",
						dataType : "json",
						data : {
							"vip.id" : vipId,
							"vip.amount" : payTotal
						},
						success : function(result){
							//var data = eval("(" + result + ")");
							console.log("储值卡余额已更新！");
							
						},
						error : function() {
							console.log("储值卡余额更新出错！")
						}
					});	
					alert("支付成功");
					location.reload(); // 强制刷新页面
				},
				error : function() {
					console.log("支付记录保存出现错误，请稍后重试！");
					
				}
			})
			
		},
		error : function() {
			console.log("出现错误，请稍后重试！")
		}
	})
	
}

// 挂账操作的函数
function debts(){
	var saleON = $("#saleOrderNo").text(); // 订单号
	var vipId = $("#vipMan").text(); // 会员ID
	var total = $("#totalMo").text(); // 总金额
	var stuffId = $("#stuffMan").text(); // 经手人ID
	var status = $("#status").text(); // 状态
	var barberId = $("#barberMan").text(); // 理发师ID

	// console.log(saleON,vipId,total,stuffId,status,barberId);
	
	// 订单表记录的插入
	$.ajax({
		type : "post",
		url : "saveSaleOrder.action",
		dataType : "json",
		data : {
			"saleOrder.saleOrderNo" : saleON,
			"saleOrder.customerNo" : vipId,
			"saleOrder.total" : total,
			"saleOrder.stuff" : stuffId,
			"saleOrder.status" : "未结算",
			"saleOrder.barber" : barberId
		},
		success : function(result){
			//var data = eval("(" + result + ")");
			console.log("订单已保存！");
			
			// 订单明细记录的插入
			var ser = $("#ItemMo");
			var pro = $("#ProductMo");
			
			if(ser.children().eq(1).attr("id")=="itemId"){ //第一条服务明细
				// 获取服务id,名称，数量
				var serId = $("#ItemMo").children().eq(1).val();
				var serName = $("#ItemMo").children().eq(2).val();
				var serCount = $("#ItemMo").children().eq(5).val();
				var serPrice = $("#ItemMo").children().eq(8).val();
				$.ajax({
					type : "post",
					url : "saveSerSaleOrderItem.action",
					dataType : "json",
					data : {
						"saleOrderItem.saleOrderNo" : saleON,
						"saleOrderItem.itemId" : serId,
						
						"saleOrderItem.quantity" : serCount,
						"saleOrderItem.salePrice" : serPrice,
						"saleOrderItem.subTotal" : serPrice*serCount
					},
					success : function(){
						//var data = eval("(" + result + ")");
						console.log("订单明细已保存！")
						
					},
					error : function() {
						console.log("出现错误，请稍后重试！")
					}
				});
				
			}
			//如果有第二条服务
			if(ser.children().eq(11).attr("id")=="itemId"){ 
				// 获取服务id,名称，数量
				var serId = $("#ItemMo").children().eq(11).val();
				var serName = $("#ItemMo").children().eq(12).val();
				var serCount = $("#ItemMo").children().eq(15).val();
				var serPrice = $("#ItemMo").children().eq(18).val();
				$.ajax({
					type : "post",
					url : "saveSerSaleOrderItem.action",
					dataType : "json",
					data : {
						"saleOrderItem.saleOrderNo" : saleON,
						"saleOrderItem.itemId" : serId,
						
						"saleOrderItem.quantity" : serCount,
						"saleOrderItem.salePrice" : serPrice,
						"saleOrderItem.subTotal" : serPrice*serCount
					},
					success : function(){
						//var data = eval("(" + result + ")");
						console.log("订单明细已保存！")
						
					},
					error : function() {
						console.log("出现错误，请稍后重试！")
					}
				});	
			}
			// 第一条产品
			if($("#ProductMo").children().eq(1).attr("id")=="proId"){ 
				console.log("有没有跳进插入产品")
				// 获取id,名称,数量,价格
				var proId = $("#ProductMo").children().eq(1).val();
				var proName = $("#ProductMo").children().eq(2).val();
				var proCount = $("#ProductMo").children().eq(5).val();
				var proPrice = $("#ProductMo").children().eq(8).val();
				$.ajax({
					type : "post",
					url : "saveProSaleOrderItem.action",
					dataType : "json",
					data : {
						"saleOrderItem.saleOrderNo" : saleON,
						"saleOrderItem.productId" : proId,
						
						"saleOrderItem.quantity" : proCount,
						"saleOrderItem.salePrice" : proPrice,
						"saleOrderItem.subTotal" : proPrice*proCount
					},
					success : function(){
						//var data = eval("(" + result + ")");
						console.log("订单明细已保存！")
						
					},
					error : function() {
						console.log("出现错误，请稍后重试！")
					}
				});	
			}
			// 如果有第二条产品
			if(pro.children().eq(11).attr("id")=="productId"){ 
				// 获取id,名称,数量,价格
				var proId = $("#ProductMo").children().eq(11).val();
				var proName = $("#ProductMo").children().eq(12).val();
				var proCount = $("#ProductMo").children().eq(15).val();
				var proPrice = $("#ProductMo").children().eq(18).val();
				$.ajax({
					type : "post",
					url : "saveProSaleOrderItem.action",
					dataType : "json",
					data : {
						"saleOrderItem.saleOrderNo" : saleON,
						"saleOrderItem.productId" : proId,
						
						"saleOrderItem.quantity" : proCount,
						"saleOrderItem.salePrice" : proPrice,
						"saleOrderItem.subTotal" : proPrice*proCount
					},
					success : function(){
						//var data = eval("(" + result + ")");
						console.log("订单明细已保存！")
						
					},
					error : function() {
						console.log("出现错误，请稍后重试！")
					}
				});	
			}
			
			console.log("挂账操作完成！");
			alert("挂账成功！");
			location.reload(); // 刷新页面
		},
		error : function() {
			console.log("挂账出现错误，请稍后重试！")
		}
	})
}

// 查出所有挂账记录
function listDebts(){
	$.ajax({
		type : "post",
		url : "listDebts.action",
		dataType : "json",
		data : {},
		success : function(result){
			var data = eval("(" + result + ")");
			$("#debtsTable tbody").html('');
			
			for(var i = 0;i<data.length;i++) {
				var d = data[i];
				$('#debtsTable tbody').append(
					'<tr>' + 
						'<td>' + d.saleOrderNo + '</td>' + 
						'<td>' + d.vipId + '</td>' + 
						'<td>' + d.vipName + '</td>' + 
						'<td>' + d.saleDateTime + '</td>' +
						'<td>' + d.total + '</td>' + 
						'<td>' + d.adminName + '</td>' +
						'<td>' + d.employeeName + '</td>' + 
						'<td>' + 
							'<span class="label label-lg label-pink arrowed arrowed-right">' +
								d.status + '</span>' +
						'</td>' +					
						'<td>' + 
							'<div class="visible-md visible-lg hidden-sm hidden-xs action-buttons">' + 
								'<button data-toggle="modal" data-target="#pDebts'+i+'" onclick="changePN()" class="btn btn-xs btn-yellow">' + 
									'<i class="icon-bolt bigger-120"> 支付</i></button>' +	
								'<button onclick="showDebtsItem(this)" class="btn btn-xs btn-info">' + 
									'<i class="icon-eye-open bigger-120"> 详情</i></button>' +
							'</div>' + 
						'</td>' +
					'</tr>'
				);
				
				// 模态框
				$("#payMo").append(
						'<div>'+
						'<div class="modal fade" id="pDebts' + i + '" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">'+
							'<div class="modal-dialog" role="document">'+
								'<div class="modal-content">'+
									'<div class="modal-header">'+
										'<button type="button" class="close" data-dismiss="modal" aria-label="Close">'+
											'<span aria-hidden="true">&times;</span>'+
										'</button>'+
										'<h4 class="modal-title" id="myModalLabel">请确认挂账订单</h4>'+
									'</div>'+
									'<div class="modal-body">'+
										'<div class="row">'+
											'<div class="col-xs-12">'+
												'<div class="form-group">'+
													'<label class="col-sm-3"> 订单号 </label> '+
													
													'<span id="saleOrderNo">'+d.saleOrderNo+'</span>'+
												'</div>'+
												'<div class="form-group">'+
													'<label class="col-sm-3"> 支付号 </label> '+
													'<span class="payN"></span>'+
													
												'</div>'+
												'<div class="form-group">'+
													'<label class="col-sm-3"> 客户ID </label> '+
													'<span id="payMoVipId">' + d.vipId + '</span>'+
												
												'</div>'+
												'<div class="form-group">'+
													'<label class="col-sm-3"> 交易方式 </label> '+
													'<select class="typeMo">'+
														'<option value="储值卡支付">储值卡支付</option>'+
														'<option value="现金支付">现金支付</option>'+
														'<option value="微信支付">微信支付</option>'+
														'<option value="支付宝支付">支付宝支付</option>'+
													'</select>'+
												'</div>'+
											'</div>'+
										'</div>'+
									'</div>'+
									'<div class="modal-footer">'+
										'<button type="button" onclick="payDebts(this)" class="btn btn-primary">支付</button>'+
									'</div>'+
								'</div>'+
							'</div>'+
						'</div>'+
					'</div>'
				);		
			}
			// datatables 初始化
			var ptable = $("#debtsTable").dataTable({				
				"paging":   false,
				"scrollY": "200px",
                "scrollCollapse": "true",
				"oLanguage" : { // 设置语言
					"sProcessing" : "正在加载中......",
					"sLengthMenu" : "每页显示 _MENU_ 条记录",
					"sZeroRecords" : "对不起，查询不到相关数据！",
					'sSearch' : '检索:',
					"sEmptyTable" : "目前还没有挂账记录",
					"sInfo" : "当前显示 _START_ 到 _END_ 条，共 _TOTAL_ 条记录",
					"sInfoFiltered" : "数据表中共为 _MAX_ 条记录",
					"oPaginate" : {
						"sFirst" : "首页",
						"sPrevious" : "上一页",
						"sNext" : "下一页",
						"sLast" : "末页"
						}
					}
			});	
			
		},
		error : function() {
			console.log("出现错误，请稍后重试！")
		}
	})
}

// 订单号，点击挂账表的支付按钮时赋值给模态框
function changePN(){
	var timestamp = Date.parse(new Date());
	pN = "pay" + timestamp;
	$(".payN").text(pN); //id只能获取一个值，要想同时改变多个值用class
}

// 挂账的支付功能
function payDebts(btnObject){
	var saleOrderNo = $(btnObject).parent().prev().children().eq(0).children().eq(0).children().eq(0).children().eq(1).text();
	
	// 挂账表格的客户ID号
	var vipId = $(btnObject).parent().prev().children().eq(0).children().eq(0).children().eq(2).children().eq(1).text();
	console.log("777777"+vipId);
	
//	var timestamp = Date.parse(new Date());
//	var payNum = "pay"+timestamp;  
	var payNum = $(btnObject).parent().prev().children().eq(0).children().eq(0).children().eq(1).children().eq(1).text();
	console.log("pn"+payNum);
	
	var payTotal  // 支付金额现在先假定同总金额
	var payType = $(".typeMo").val(); //支付方式
	var payMan  // 收款人现在先假定同经手人
	
	$.ajax({
		type : "post",
		url : "getOneSaleOrder.action",
		dataType : "json",
		data : {
			"saleOrder.saleOrderNo" : saleOrderNo
		},
		success : function(result){
			var data = eval("(" + result + ")");
			console.log("111222"+data);
			
			payTotal = data[0].total;
			payMan = data[0].adminId;
			console.log(payTotal,payMan);
			
			// 改变订单的状态
			$.ajax({
				type : "post",
				url : "updateSO.action",
				dataType : "json",
				data : {
					"saleOrder.saleOrderNo" : saleOrderNo	
				},
				success : function(result){
					console.log("订单表状态已改变！");
					
					// 支付表记录的插入
					$.ajax({
						type : "post",
						url : "savePayment.action",
						dataType : "json",
						data : {
							"payment.saleOrderNo" : saleOrderNo,
							"payment.paymentNo" : payNum,
							"payment.amount" : payTotal,
							"payment.payType" : payType,
							"payment.stuff" : payMan	
						},
						success : function(result){
							//var data = eval("(" + result + ")");
							console.log("支付记录已保存！");
							
							// 减去储值卡余额的操作
							$.ajax({
								type : "post",
								url : "changeVipAmount.action",
								dataType : "json",
								data : {
									"vip.id" : vipId,
									"vip.amount" : payTotal
								},
								success : function(result){
									//var data = eval("(" + result + ")");
									console.log("储值卡余额已更新！");
									
									
								},
								error : function() {
									console.log("储值卡余额更新出错！")
								}
							});	
							alert("支付成功！");
							location.reload(); // 强制刷新页面
						},
						error : function() {
							console.log("出现错误，请稍后重试！");
							//location.reload();
							
						}
					})
					
				},
				error : function() {
					console.log("订单状态改变出现错误，请稍后重试！");
				}
			})
			
			
			
		},
		error : function() {
			console.log("出现错误，请稍后重试！")
		}
	});	
	
}
// 添加会员
function saveVip(btnObject){
	var name = $("#vipName").val();
	var phone = $("#vipPhone").val();
	var sex = $("#vipSex").val();
	var rechargeAmount = $("#vipRechargeAmount").val(); // 充值金额
	var remark = $("#vipRemark").val();
	console.log(name,phone,sex,remark,rechargeAmount);
	
	var type = ""; //会员等级
	if (rechargeAmount <= 1000) {
		type = "普通会员";
	} else if (rechargeAmount <= 2000) {
		type = "银卡会员";
	} else if (rechargeAmount <= 3000) {
		type = "金卡会员";
	} else {
		type = "黑卡会员";
	}
	
	// 判断姓名，充值金额非空
	if(name == null || name == "" || rechargeAmount == null || rechargeAmount == ""){
		alert("请检查会员姓名或充值金额是否已经填写！");
		return false;
	}else {
		$.ajax({
			type : "post",
			url : "saveVip.action",
			dataType : "json",
			data : { // 发送到服务器的数据
				"vip.name" : name,
				"vip.phone" : phone,
				"vip.sex" : sex,
				"vip.rechargeAmount" : rechargeAmount,
				"vip.type" : type,
				"vip.remark" : remark
			},
			success : function(result) {
				console.log(result);
				alert("会员添加成功！");
				location.reload(); //强制页面刷新。。异步何用？
			},
			error : function() {
				alert("会员添加失败，请稍后再试！");
				return false;
			}
		});
	}
}
// 根据选择的会员查询其总充值金额和储值卡余额，等级
function checkRechAndAmount(btnObject){
	var vipId = $(".selectVip").val();
	console.log("选择的会员ID"+vipId);
	
	$.ajax({
		type : "post",
		url : "getOneVip.action",
		dataType : "json",
		data : { // 发送到服务器的数据
			"vip.id" : vipId
		},
		success : function(result) {
			var data = eval("(" + result + ")");
			
			$("#vipRechargeAll").val(data[0].rechargeAmount);
			$("#vipAmountAll").val(data[0].amount);
			$("#vType").text(data[0].type);
					
		},
		error : function() {
			console.log("失败，请稍后再试！");
			return false;
		}
	});	
}
// 根据填入充值金额充值后等级变为
function changeType(btnObject){
	var rechargeAmount = $("#rechargeAmount").val(); //待充值的金额
	var rechargeAll = $("#vipRechargeAll").val(); // 原先充值总金额
	
	var changeAmount = Number(rechargeAmount) + Number(rechargeAll);
	console.log(changeAmount);
	// 判断等级
	if (changeAmount <= 1000) {
		$("#chaType").text("普通会员");
	} else if (changeAmount <= 2000){
		$("#chaType").text("银卡会员");
	} else if (changeAmount <= 3000){
		$("#chaType").text("金卡会员");
	} else {
		$("#chaType").text("黑卡会员");
	}
}
// 充值功能
function rechargeForVip(btnObject){
	var rechargeAmount = $("#rechargeAmount").val();
	var vipId = $(".selectVip").val();
	console.log(vipId,rechargeAmount);
	
	$.ajax({
		type : "post",
		url : "rechargeForVip.action",
		dataType : "json",
		data : {
			"vip.id" : vipId,
			"vip.rechargeAmount" : rechargeAmount
		},
		success : function(result){
			var data = eval("(" + result + ")");
			
			alert("充值成功！用户："+data[0].name+"的储值卡余额为"+data[0].amount+
					",充值总金额为"+data[0].rechargeAmount+"。");
			location.reload();
		},
		error : function(){
			console.log("失败，请稍后再试！");
			return false;
		}
	})
}








/* 我将原本模板index页的js删掉，加上form-elements页的js，就可以用选择框 */
jQuery(function($) {
	$('#id-disable-check').on('click', function() {
		var inp = $('#form-input-readonly').get(0);
		if(inp.hasAttribute('disabled')) {
			inp.setAttribute('readonly' , 'true');
			inp.removeAttribute('disabled');
			inp.value="This text field is readonly!";
		}
		else {
			inp.setAttribute('disabled' , 'disabled');
			inp.removeAttribute('readonly');
			inp.value="This text field is disabled!";
		}
	});


	$(".chosen-select").chosen(); 
	$('#chosen-multiple-style').on('click', function(e){
		var target = $(e.target).find('input[type=radio]');
		var which = parseInt(target.val());
		if(which == 2) $('#form-field-select-4').addClass('tag-input-style');
		 else $('#form-field-select-4').removeClass('tag-input-style');
	});
	


	$('[data-rel=tooltip]').tooltip({container:'body'});
	$('[data-rel=popover]').popover({container:'body'});
	
	$('textarea[class*=autosize]').autosize({append: "\n"});
	$('textarea.limited').inputlimiter({
		remText: '%n character%s remaining...',
		limitText: 'max allowed : %n.'
	});

	$.mask.definitions['~']='[+-]';
	$('.input-mask-date').mask('99/99/9999');
	$('.input-mask-phone').mask('(999) 999-9999');
	$('.input-mask-eyescript').mask('~9.99 ~9.99 999');
	$(".input-mask-product").mask("a*-999-a999",{placeholder:" ",completed:function(){alert("You typed the following: "+this.val());}});



	$( "#input-size-slider" ).css('width','200px').slider({
		value:1,
		range: "min",
		min: 1,
		max: 8,
		step: 1,
		slide: function( event, ui ) {
			var sizing = ['', 'input-sm', 'input-lg', 'input-mini', 'input-small', 'input-medium', 'input-large', 'input-xlarge', 'input-xxlarge'];
			var val = parseInt(ui.value);
			$('#form-field-4').attr('class', sizing[val]).val('.'+sizing[val]);
		}
	});

	$( "#input-span-slider" ).slider({
		value:1,
		range: "min",
		min: 1,
		max: 12,
		step: 1,
		slide: function( event, ui ) {
			var val = parseInt(ui.value);
			$('#form-field-5').attr('class', 'col-xs-'+val).val('.col-xs-'+val);
		}
	});
	
	
	$( "#slider-range" ).css('height','200px').slider({
		orientation: "vertical",
		range: true,
		min: 0,
		max: 100,
		values: [ 17, 67 ],
		slide: function( event, ui ) {
			var val = ui.values[$(ui.handle).index()-1]+"";

			if(! ui.handle.firstChild ) {
				$(ui.handle).append("<div class='tooltip right in' style='display:none;left:16px;top:-6px;'><div class='tooltip-arrow'></div><div class='tooltip-inner'></div></div>");
			}
			$(ui.handle.firstChild).show().children().eq(1).text(val);
		}
	}).find('a').on('blur', function(){
		$(this.firstChild).hide();
	});
	
	$( "#slider-range-max" ).slider({
		range: "max",
		min: 1,
		max: 10,
		value: 2
	});
	
	$( "#eq > span" ).css({width:'90%', 'float':'left', margin:'15px'}).each(function() {
		// read initial values from markup and remove that
		var value = parseInt( $( this ).text(), 10 );
		$( this ).empty().slider({
			value: value,
			range: "min",
			animate: true
			
		});
	});

	
	$('#id-input-file-1 , #id-input-file-2').ace_file_input({
		no_file:'No File ...',
		btn_choose:'Choose',
		btn_change:'Change',
		droppable:false,
		onchange:null,
		thumbnail:false //| true | large
		//whitelist:'gif|png|jpg|jpeg'
		//blacklist:'exe|php'
		//onchange:''
		//
	});
	
	$('#id-input-file-3').ace_file_input({
		style:'well',
		btn_choose:'Drop files here or click to choose',
		btn_change:null,
		no_icon:'icon-cloud-upload',
		droppable:true,
		thumbnail:'small'//large | fit
		//,icon_remove:null//set null, to hide remove/reset button
		/**,before_change:function(files, dropped) {
			//Check an example below
			//or examples/file-upload.html
			return true;
		}*/
		/**,before_remove : function() {
			return true;
		}*/
		,
		preview_error : function(filename, error_code) {
			//name of the file that failed
			//error_code values
			//1 = 'FILE_LOAD_FAILED',
			//2 = 'IMAGE_LOAD_FAILED',
			//3 = 'THUMBNAIL_FAILED'
			//alert(error_code);
		}

	}).on('change', function(){
		//console.log($(this).data('ace_input_files'));
		//console.log($(this).data('ace_input_method'));
	});
	

	//dynamically change allowed formats by changing before_change callback function
	$('#id-file-format').removeAttr('checked').on('change', function() {
		var before_change
		var btn_choose
		var no_icon
		if(this.checked) {
			btn_choose = "Drop images here or click to choose";
			no_icon = "icon-picture";
			before_change = function(files, dropped) {
				var allowed_files = [];
				for(var i = 0 ; i < files.length; i++) {
					var file = files[i];
					if(typeof file === "string") {
						//IE8 and browsers that don't support File Object
						if(! (/\.(jpe?g|png|gif|bmp)$/i).test(file) ) return false;
					}
					else {
						var type = $.trim(file.type);
						if( ( type.length > 0 && ! (/^image\/(jpe?g|png|gif|bmp)$/i).test(type) )
								|| ( type.length == 0 && ! (/\.(jpe?g|png|gif|bmp)$/i).test(file.name) )//for android's default browser which gives an empty string for file.type
							) continue;//not an image so don't keep this file
					}
					
					allowed_files.push(file);
				}
				if(allowed_files.length == 0) return false;

				return allowed_files;
			}
		}
		else {
			btn_choose = "Drop files here or click to choose";
			no_icon = "icon-cloud-upload";
			before_change = function(files, dropped) {
				return files;
			}
		}
		var file_input = $('#id-input-file-3');
		file_input.ace_file_input('update_settings', {'before_change':before_change, 'btn_choose': btn_choose, 'no_icon':no_icon})
		file_input.ace_file_input('reset_input');
	});




	$('#spinner1').ace_spinner({value:0,min:0,max:200,step:10, btn_up_class:'btn-info' , btn_down_class:'btn-info'})
	.on('change', function(){
		//alert(this.value)
	});
	$('#spinner2').ace_spinner({value:0,min:0,max:10000,step:100, touch_spinner: true, icon_up:'icon-caret-up', icon_down:'icon-caret-down'});
	$('#spinner3').ace_spinner({value:0,min:-100,max:100,step:10, on_sides: true, icon_up:'icon-plus smaller-75', icon_down:'icon-minus smaller-75', btn_up_class:'btn-success' , btn_down_class:'btn-danger'});


	
	$('.date-picker').datepicker({autoclose:true}).next().on(ace.click_event, function(){
		$(this).prev().focus();
	});
	$('input[name=date-range-picker]').daterangepicker().prev().on(ace.click_event, function(){
		$(this).next().focus();
	});
	
	$('#timepicker1').timepicker({
		minuteStep: 1,
		showSeconds: true,
		showMeridian: false
	}).next().on(ace.click_event, function(){
		$(this).prev().focus();
	});
	
	$('#colorpicker1').colorpicker();
	$('#simple-colorpicker-1').ace_colorpicker();

	
	$(".knob").knob();
	
	
	//we could just set the data-provide="tag" of the element inside HTML, but IE8 fails!
	var tag_input = $('#form-field-tags');
	if(! ( /msie\s*(8|7|6)/.test(navigator.userAgent.toLowerCase())) ) 
	{
		tag_input.tag(
		  {
			placeholder:tag_input.attr('placeholder'),
			//enable typeahead by specifying the source array
			source: ace.variable_US_STATES,//defined in ace.js >> ace.enable_search_ahead
		  }
		);
	}
	else {
		//display a textarea for old IE, because it doesn't support this plugin or another one I tried!
		tag_input.after('<textarea id="'+tag_input.attr('id')+'" name="'+tag_input.attr('name')+'" rows="3">'+tag_input.val()+'</textarea>').remove();
		//$('#form-field-tags').autosize({append: "\n"});
	}
	
	
	

	/////////
	$('#modal-form input[type=file]').ace_file_input({
		style:'well',
		btn_choose:'Drop files here or click to choose',
		btn_change:null,
		no_icon:'icon-cloud-upload',
		droppable:true,
		thumbnail:'large'
	})
	
	//chosen plugin inside a modal will have a zero width because the select element is originally hidden
	//and its width cannot be determined.
	//so we set the width after modal is show
	$('#modal-form').on('shown.bs.modal', function () {
		$(this).find('.chosen-container').each(function(){
			$(this).find('a:first-child').css('width' , '210px');
			$(this).find('.chosen-drop').css('width' , '210px');
			$(this).find('.chosen-search input').css('width' , '200px');
		});
	})
	/**
	//or you can activate the chosen plugin after modal is shown
	//this way select element becomes visible with dimensions and chosen works as expected
	$('#modal-form').on('shown', function () {
		$(this).find('.modal-chosen').chosen();
	})
	*/

});